package com.outdoor.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.outdoor.common.constant.MessageConstant;
import com.outdoor.common.exception.LoginFailedException;
import com.outdoor.common.properties.WeChatProperties;
import com.outdoor.common.result.PageResult;
import com.outdoor.common.utils.HttpClientUtil;
import com.outdoor.pojo.dto.UserLoginDTO;
import com.outdoor.pojo.dto.UserPageQueryDTO;
import com.outdoor.pojo.dto.UserPermissionDTO;
import com.outdoor.pojo.entity.User;
import com.outdoor.server.mapper.UserMapper;
import com.outdoor.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    /**
     * 分页查询用户信息
     * @param userPageQueryDTO
     * @return
     */
    public PageResult page(UserPageQueryDTO userPageQueryDTO) {
        PageHelper.startPage(userPageQueryDTO.getPage(), userPageQueryDTO.getPageSize());
        Page<User> page = userMapper.page(userPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }


    /**
     * 根据id查询用户信息
     * @param id
     * @return
     */
    public User getUserById(Long id) {
        return userMapper.getUserById(id);
    }

    /**
     * 更新用户权限
     * @param userPermissionDTO
     */
    @Override
    @Transactional
    public void updateUserPermission(UserPermissionDTO userPermissionDTO) {
        User user = userMapper.getUserById(userPermissionDTO.getId());
        if (user == null) {
            throw new RuntimeException("用戶不存在");
        }

        // 更新用戶权限
        user.setPermissions(userPermissionDTO.getPermissions());
        
        // 根据用戶权限更新用戶类型
        // 如果用戶有任何权限（permission > 0），則设置为高級用戶（type = 1）
        user.setType(userPermissionDTO.getPermissions() > 0 ? 1 : 0);
        
        userMapper.updateUser(user);
    }

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    public User wxLogin(UserLoginDTO userLoginDTO) {
        String openid = getOpenid(userLoginDTO.getCode());
        //判断openid是否存在，如果为空表示登录失败，抛出业务异常
        if(openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断当前用户用户是否为新用户
        User user = userMapper.getByOpenid(openid);
        //如果是新用户，则更新用户信息
        if(user == null){
            user= User.builder()
                    .openid(openid)
                    .createdTime(LocalDateTime.now())
                    .follow(0)
                    .fans(0)
                    .type(0)
                    .permissions(0)
                    .build();
            userMapper.insert(user);
        }
        //返回用户信息
        return user;
    }


    /**
     * 调用微信接口，获取微信用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code) {
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN,map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
